public class SpiralMatrix {
    public static int[][] generateSpiralMatrix(int n) {
        // 初始化一个n x n的矩阵，所有元素都设为0
        int[][] matrix = new int[n][n];

        // 定义边界
        int top = 0;
        int bottom = n - 1;
        int left = 0;
        int right = n - 1;

        // 依次从1开始累加
        int num = 1;

        while (top <= bottom && left <= right) {
            // 从左到右填充顶部边界
            for (int i = left; i <= right; i++) {
                matrix[top][i] = num++;
            }
            top++;

            // 从上到下填充右侧边界
            for (int i = top; i <= bottom; i++) {
                matrix[i][right] = num++;
            }
            right--;

            // 检查是否还有需要填充的区域
            if (top <= bottom) {
                // 从右到左填充底部边界
                for (int i = right; i >= left; i--) {
                    matrix[bottom][i] = num++;
                }
                bottom--;
            }

            if (left <= right) {
                // 从下到上填充左侧边界
                for (int i = bottom; i >= top; i--) {
                    matrix[i][left] = num++;
                }
                left++;
            }

        }
        return matrix;
    }

    public static void printMatrix(int[][] matrix) {
        // for-each来遍历结果集
        for (int[] row : matrix) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int n = 7; // 可以修改这个值来生成不同大小的螺旋矩阵
        int[][] spiralMatrix = generateSpiralMatrix(n);
        printMatrix(spiralMatrix);
    }
}